package org.example.l0;

import org.junit.jupiter.api.Test;

import java.util.*;

public class findSubstring {

    @Test
    void run() {
        List<Integer> barfoothefoobarman = findSubstring("wordgoodgoodgoodbestword", new String[]{"word", "good", "best", "good"});
    }

    public List<Integer> findSubstring(String s,
                                       String[] words) {

        int arrLen = words.length, wordLen = words[0].length(), strLen = s.length();
        List<Integer> res = new ArrayList<>();
        for (int skip = 0; skip < wordLen; skip++) {
            List<String> subList = getSubList(s, skip, wordLen, strLen);
            for (int i = 0; i <= subList.size() - arrLen; i++) {
                Map<String, Integer> map = new HashMap<>();
                List<String> list2 = subList.subList(i, i + arrLen);
                list2.forEach(s1 -> map.put(s1, map.getOrDefault(s1, 0) + 1));
                Arrays.stream(words).forEach(word -> map.put(word, map.getOrDefault(word, 0) - 1));
                Optional<Integer> any = map.values().stream().filter(v -> v != 0).findAny();
                if (!any.isPresent()) {
                    res.add(i * wordLen + skip);
                }
            }
        }

        return res;
    }

    private static List<String> getSubList(String s,
                                           int skip,
                                           int wordLen,
                                           int strLen) {
        List<String> subList = new ArrayList<>();
        for (int i = skip; i + wordLen <= strLen; i += wordLen) {
            subList.add(s.substring(i, i + wordLen));
        }
        return subList;
    }
}
